//
//  WNSubManager.swift
//  WalkNovel
//
//  Created by Kevin on 2023/9/7.
//

import UIKit
import SwiftyStoreKit
import StoreKit

//MARK: - 苹果支付订阅
class WNSubManager: NSObject {
    
    static let shared = WNSubManager()
    
    /// 创建订阅订单
    func creatSubscribeOrder(_ pid: String, _ price: Double) {
        WNBuriedManager.shared.initiatedCheckout(price)
        WNHUD.wn_showLiveAnimateLoading()
        provider_pay.rx.request(.creatSubscribeOrder(pid))
            .asObservable().mapModel(BaseModel<String>.self)
            .subscribe(onNext: { [weak self] (model) in
                guard model.code == 0 else {
                    WNHUD.wn_show(model.msg ?? "")
                    return
                }
                if let orderId = model.data {
                    WNBuriedManager.shared.addedPaymentInfo(price)
                    self?.buySubscribe(orderId, pid, price)
                }else {
                    WNHUD.wn_hide()
                }
            }, onError: { (error) in
                WNHUD.wn_show("檢查網路連線")
            }).disposed(by: rx.disposeBag)
    }
    
    /// 调起苹果支付订阅订单
    func buySubscribe(_ orderId: String, _ productId: String, _ price: Double = 0.0) {
        isAppleLogin() ? setUserIdSubOrderId(orderId) : setUuidSubOrderId(orderId)
        var dic = [String: Any]()
        SwiftyStoreKit.purchaseProduct(productId) { [weak self] result in
            switch result {
            case let .success(purchase):
                var code: Int = 1
                var state: SKPaymentTransactionState?
                var tid = ""
                // 如果是自动续费的订单,originalTransaction会有内容
                if purchase.originalTransaction != nil {
                    state = purchase.originalTransaction?.transactionState
                    tid = purchase.originalTransaction?.transactionIdentifier ?? ""
                }else {
                    state = purchase.transaction.transactionState
                    tid = purchase.transaction.transactionIdentifier ?? ""
                }
                switch state {
                case .purchased, .restored: code = 0
                default: break
                }
                if code == 0 {
                    WNBuriedManager.shared.purchase(price)
                }
                let receipt = SwiftyStoreKit.localReceiptData?.base64EncodedString()
                dic["code"] = code
                dic["msg"] = ""
                dic["orderId"] = orderId
                dic["tid"] = tid
                dic["receipt"] = receipt
                dic["price"] = price
                self?.verifySubscribe(dic, purchase)
            case let .error(error):
                var msg = "購買錯誤"
                switch error.code {
                case .paymentCancelled:
                    msg = "您已取消付款"
                case .paymentInvalid:
                    msg = "無效產品"
                default:
                    break
                }
                dic["code"] = 2
                dic["msg"] = msg
                dic["orderId"] = orderId
                self?.verifySubscribe(dic)
            }
        }
    }
    
    /// 苹果支付校验凭证
    func verifySubscribe(_ dic: [String: Any], _ purchase: PurchaseDetails? = nil) {
        let code = dic["code"] as? Int
        let msg = dic["msg"] as? String ?? ""
        let orderId = dic["orderId"] as? String ?? ""
        let tid = dic["tid"] as? String ?? ""
        let receipt = dic["receipt"] as? String ?? ""
        let price = dic["price"] as? Double ?? 0.0
        guard !isBlank(orderId) else {
            return
        }
        provider_pay.rx.request(.verifySubscribe(orderId, tid, receipt))
            .asObservable().mapModel(BaseModel<Any>.self)
            .subscribe(onNext: { model in
                guard model.code == 0 else {
                    WNHUD.wn_show(model.msg ?? "")
                    return
                }
                if let pur = purchase, pur.needsFinishTransaction {
                    SwiftyStoreKit.finishTransaction(pur.transaction)
                }
                if code == 0 {
                    isAppleLogin() ? setUserIdSubOrderId("") : setUuidSubOrderId("")
                    WNHUD.wn_show("訂閱成功！")
                    WNBuriedManager.shared.purchased(price)
                    NotificationCenter.default.post(name: WNNotiName.subscribeNoti, object: nil)
                }else {
                    WNHUD.wn_show(msg)
                }
            }, onError: { (error) in
                WNHUD.wn_show("檢查網路連線")
            }).disposed(by: rx.disposeBag)
    }
    
    func restoreSubscribe(_ productId: String, _ secret: String) {
        SwiftyStoreKit.verifyReceipt(using: AppleReceiptValidator(service: server.isProduct ? .production : .sandbox, sharedSecret: secret)) { result in
            switch result {
            case .success(let receipt):
                let purchaseResult = SwiftyStoreKit.verifySubscription(ofType: .autoRenewable, productId: productId, inReceipt: receipt)
                switch purchaseResult {
                case .purchased(let expiryDate, let items):
                    print("\(productId) is valid until \(expiryDate)\n\(items)\n")
                case .expired(let expiryDate, let items):
                    print("\(productId) is expired since \(expiryDate)\n\(items)\n")
                case .notPurchased:
                    print("The user has never purchased \(productId)")
                }
            case .error(let error):
                print("Receipt verification failed: \(error)")
            }
        }
    }
}
